import config from "./config";

const httpRequest = async (options) => {
	let {
		url,
		data,
		object
	} = options;
	let baseUrl = "";

	if (object === "platform") {
		baseUrl = config.merchantServicePlatformUrl;
	}

	if (object === "organization") {
		baseUrl = config.organizationGateway; //"http://127.0.0.1:9999";
	}

	const organizationUuid = config.organizationUuid;

	const BASE_URL = baseUrl;

	const showError = options.showError === false ? false : true;

	const requestOptions = {
		dataType: "json",
		data,
		url: `${BASE_URL}${url}`,
		method: options.method || "POST",
		header: {
			"Content-Type": "application/json;charset=UTF-8",
			organizationUuid,
		},
	};

	try {
		const res = await uni.request(requestOptions);

		if (res.statusCode !== 200) {
			showError && uni.$u.toast("请求错误:" + res.statusCode);
			return null;
		}

		let {
			statusCode,
			message,
			result
		} = res.data;

		if (statusCode === 1) {
			return null;
		}

		if (statusCode > 1) {
			showError && console.error(requestOptions, statusCode, message, result);
			showError && uni.$u.toast("请求错误:" + message);
			return null;
		}

		return result ? result : true;
	} catch (error) {
		showError && console.error(error);
		showError && error?.errMsg && uni.$u.toast(error.errMsg);
		return null;
	}
};

export default httpRequest;
